package com.wayin.lift.socket;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * @Desc 服务端线程
 * @author BYzl
 * 
 */
public class Socket_Device implements Runnable {

	private static final int PORT = 4642;
	private static final String CHARSET = "UTF-8";
	public static List<Socket> sockets = new ArrayList<>();
	ServerSocket server = null;

	public Socket_Device() {
		try {
			server = new ServerSocket(PORT);		
			System.out.println("设备客户端Socket服务启动成功~");
		} catch (IOException e) {
			System.out.println("初始化Socket服务异常:\n");
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			while (true) {
				// 建立socket接口,accept方法等到用户连接才会继续执行
				Socket socket = server.accept();
				socket.setKeepAlive(true);
				// 在服务器显示连接的电脑
				String message = socket.getInetAddress().getHostAddress().toString();
				System.out.println("设备端：" + message + "已连接~");
				// 将已有的连接添加到集合中
				sockets.add(socket);     
				
				// 向客户端发送登录信息
				SendMessageToClient(message);
				
				// 建立读取客户端数据的线程
				Thread t = new Thread(new ReadClientDataThread(socket));
				t.start();
				
				//创建读取监控socket的心跳
				/*Thread thread=new Thread(new Socket_Task(socket,"device"));
				
				thread.start();*/
			}
		} catch (Exception e) {
			System.out.println("Socket运行中出现了异常：\n");
			e.printStackTrace();
		}
	}

	public static void SendMessageToClient(String message) {
		// 遍历集合,寻找已经链接的客户端
		for (Socket s : sockets) {
			// 判断是否已经连接
//			System.out.println(message);
			try {
			    if (null != s && !s.isClosed()) {
					OutputStream os = s.getOutputStream();
					os.write(message.getBytes(CHARSET));
					os.flush();								
			    }
			} catch (Exception e) {
				Socket_Task socket_task = new Socket_Task(s, "device");
				socket_task.run();
				System.gc();
				System.out.println("Socket服务向客户端发送数据出现了异常:\n");
				e.printStackTrace();
			}
		}
	}

}
